package cn.framelife.rainbow.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.util.ArrayList;
import java.util.List;

import org.eclipse.core.runtime.FileLocator;

import rainbow.Activator;

/**
 * 文件工具类
 *
 * @ClassName: FileUtil 
 * @author 潘广伟  p_3er@qq.com 
 * @date 2013年11月22日 下午3:38:46 
 *
 */
public class FileUtil {
	/**
	 * 获取插件的目录路径
	 *
	 * @Title: getPlugPath 
	 * @param @return
	 * @param @throws Exception  
	 * @return String  
	 * @throws
	 */
	private static String getPlugPath() throws Exception{
		String path = FileLocator.resolve(Activator.getDefault().getBundle().getEntry("")).getFile();
		path = new File(path).getParentFile().getParent();
		if(path.startsWith("file:")){
			path = path.substring(6);
		}
		path = StringUtil.merge("/",path,"/resource");
		/**
		 * 测试使用
		 */
//		path = FileLocator.resolve(Activator.getDefault().getBundle().getEntry("/")).getFile();
		return path;	
		
	}
	
	/**
	 * 获取web项目的WebRoot文件夹的名字
	 * 
	 * @param projectName
	 * @return
	 * @add p_3er@qq.com 2014年1月9日 上午10:57:24
	 */
	public static String getWebRootName(String projectName){
		String projectPath = ProjectUtil.getProjectPath(projectName);
		File[] files = (new File(projectPath)).listFiles();
		String webRootName = "WebRoot";
		flag : for(File file : files){
			if(file.isDirectory()){
				File[] sonFiles = file.listFiles();
				for(File f : sonFiles){
					if(f.getName().equals("WEB-INF")){
						webRootName = file.getName();
						break flag;
					}
				}
			}
		}
		
		return StringUtil.merge(projectPath,File.separator,webRootName);
	}
	
	/**
	 * 获取资源文件路径
	 *
	 * @param fileName
	 * @return
	 * @throws Exception
	 */
	public static File getFile(String fileName) throws Exception{
		return new File(StringUtil.merge(getPlugPath(),File.separator,fileName));
	}
	
	/**
	 * 拷贝JAR包到工程/WebRoot/WEB-INF/lib目录下
	 *
	 * @Title: copyJARsToProject 
	 * @param @param projectPath
	 * @param @throws Exception  
	 * @return void  
	 * @throws
	 */
	public static void copyJARsToProject(String projectName) throws Exception{
		String libPath = StringUtil.merge(getWebRootName(projectName),"/WEB-INF/lib");
		String jarsPath = StringUtil.merge(FileUtil.getPlugPath(),"/jars");
		copyJARs(jarsPath, libPath);
		copyJARs(DatabaseCache.getConnectionProperty().getJarURL(), libPath);
	}
	
	/**
	 * 复制Util类
	 *
	 * @param projectName
	 * @throws Exception
	 */
	public static void copyUtilClass(String projectName) throws Exception{
		copyClass(getPackagePath(projectName, "cn.jrainbow.util"), StringUtil.merge(FileUtil.getPlugPath(),"/template/util"));
	}
	
	/**
	 * 复制BaseDao
	 *
	 * @param projectName
	 * @throws Exception
	 */
	public static void copyBaseDaoClass(String projectName) throws Exception{
		copyClass(getPackagePath(projectName, "cn.jrainbow.base"), StringUtil.merge(FileUtil.getPlugPath(),"/template/base"));
	}

	private static void copyClass(String targetDir, String srcDir)
			throws Exception {
		File srcPath = new File(srcDir);
		createPath(targetDir);
		if (srcPath.exists() && srcPath.isDirectory()) {
			String[] files = srcPath.list();
			for(String srcName: files){
				if(srcName.endsWith(".java")){
					String targetName = StringUtil.merge(targetDir,File.separator,srcName);
					if(!new File(targetName).exists()){
						copyFile(StringUtil.merge(srcDir,File.separator,srcName),targetName);
					}
				}
			}
		}
	}
	
	
	/**
	 * 复制页面相关的文件
	 *
	 * @param targetDir
	 * @throws Exception
	 */
	public static void copyPageCommon(String projectName) throws Exception{
		String targetDir = getWebRootName(projectName);
		String srcDir = StringUtil.merge(getPlugPath(),"/pages");
		copyDirectiory(srcDir, targetDir);
	}
	
	/**
	 * 创建文件夹
	 *
	 * @Title: createPath 
	 * @param @param path  
	 * @return void  
	 * @throws
	 */
	public static void createPath(String pathURL){
		File path = new File(StringUtil.replaceSeparator(pathURL));
		
		if(!path.exists()){
			path.mkdirs();
		}
	}
	
	/**
	 * 获取包路径
	 *
	 * @Title: getPackagePath 
	 * @param  projectName
	 * @param  packageURL   
	 * @return String  
	 * @throws
	 */
	public static String getPackagePath(String projectName, String packageURL) {
		return StringUtil.merge(ProjectUtil.getProjectPath(projectName),"/src/",packageURL.replace(".", File.separator),File.separator);
	}	
	
	/**
	 * 获取web.xml的路径
	 *
	 * @param projectName
	 * @return
	 */
	public static String getWebConfigPath(String projectName){
		return StringUtil.merge(FileUtil.getWebRootName(projectName),"/WEB-INF/web.xml");
	}
	
	/**
	 * 获取Spring配置文件的路径
	 *
	 * @param projectName
	 * @return
	 */
	public static String getSpringConfigPath(String projectName){
		return StringUtil.merge(getSrcPath(projectName),"applicationContext.xml");
	}
	
	/**
	 * 获取MenuData.json的路径
	 *
	 * @param projectName
	 * @return
	 */
	public static String getMenuDataPath(String projectName){
		return StringUtil.merge(getSrcPath(projectName),"MenuData.json");
	}
	
	/**
	 * 获取包的子包名
	 *
	 * @param father
	 */
	public static List<String> getChildPackage(String projectName,String fatherPackage){
		List<String> children = new ArrayList<String>();
		String path = getSrcPath(projectName);
		if(!fatherPackage.equals("/src")){
			path = getPackagePath(projectName, fatherPackage);
		}
		File[] files = new File(path).listFiles();
		for(File file : files){
			if(file.isDirectory()){
				children.add(file.getName());
			}
		}
		return children;
	}
	
	/**
	 * 获取src路径
	 *
	 * @param projectName
	 * @return
	 */
	private static String getSrcPath(String projectName){
		return StringUtil.merge(ProjectUtil.getProjectPath(projectName),"/src/");
	}
	
	/**
	 * 文件拷贝
	 *
	 * @Title: copyFile 
	 * @param @param src 源文件
	 * @param @param target 目标文件
	 * @param @throws Exception  
	 * @return void  
	 * @throws
	 */
	private static void copyFile(String src,String target) throws Exception{
        FileChannel fcin = new FileInputStream(src).getChannel();  
        FileChannel fcout =  new FileOutputStream(target).getChannel();  
        ByteBuffer buffer = ByteBuffer.allocate(1024);  
        while (true) {  
            buffer.clear();  
            int r = fcin.read(buffer);  
            if (r == -1) {  
                break;  
            }  
            buffer.flip();  
            fcout.write(buffer);  
        }  
	}
	
	/**
	 * 拷贝文件夹及其文件
	 *
	 * @param sourceDir
	 * @param targetDir
	 * @throws Exception
	 */
	private static void copyDirectiory(String sourceDir, String targetDir)
			throws Exception {
		(new File(targetDir)).mkdirs();
		File[] file = (new File(sourceDir)).listFiles();
		for (int i = 0; i < file.length; i++) {
			if (file[i].isFile()) {
				String sourceFile = file[i].getPath();
				String targetFile = StringUtil.merge(new File(targetDir).getAbsolutePath()
						, File.separator , file[i].getName());
				copyFile(sourceFile, targetFile);
			}
			if (file[i].isDirectory()) {
				String srcPath = StringUtil.merge(sourceDir, File.separator, file[i].getName());
				String targetPath = StringUtil.merge(targetDir, File.separator, file[i].getName());
				copyDirectiory(srcPath, targetPath);
			}
		}
	} 
	
	/**
	 * 
	 * 批量拷贝JAR包
	 *
	 * @Title: copyJARs 
	 * @param @param srcDir
	 * @param @param targetDir  
	 * @return void  
	 * @throws Exception
	 */
	private static void copyJARs(String srcDir, String targetDir) throws Exception{
		File srcPath = new File(srcDir);
		if(srcPath.exists()){
			if (srcPath.isDirectory()) {
				String[] files = srcPath.list();
				for(String srcName: files){
					if(srcName.endsWith(".jar")){
						copyFile(StringUtil.merge(srcDir,File.separator,srcName), StringUtil.merge(targetDir,"\\",srcName));
					}
				}
			}else if(!srcPath.isDirectory()){
				if(srcDir.endsWith(".jar")){
					copyFile(srcDir,StringUtil.merge(targetDir,File.separator,srcPath.getName()));
				}
			}
		}
		
	}
	
}
